// api.js - API服务模块
import { logInfo, logError } from '../logger';

// API基础URL - 使用相对路径通过代理访问
const API_BASE_URL = '/api';

/**
 * API服务类
 */
class ApiService {
  /**
   * 构造函数
   */
  constructor() {
    this.baseUrl = API_BASE_URL;
  }

  /**
   * 获取认证头部
   * @returns {Object} 包含Authorization头部的对象
   */
  getAuthHeaders() {
    const token = localStorage.getItem('token');
    return token ? { Authorization: `Bearer ${token}` } : {};
  }

  /**
   * 通用请求方法
   * @param {string} endpoint - API端点
   * @param {Object} options - 请求选项
   * @returns {Promise} 请求Promise
   */
  async request(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...this.getAuthHeaders(),
        ...options.headers,
      },
      ...options,
    };

    try {
      logInfo(`发起API请求: ${options.method || 'GET'} ${endpoint}`);
      const response = await fetch(url, config);
      const data = await response.json();

      if (!response.ok) {
        logError(`API请求失败: ${response.status} ${endpoint}`, { 
          status: response.status, 
          message: data.message 
        });
        throw new Error(data.message || '请求失败');
      }

      logInfo(`API请求成功: ${options.method || 'GET'} ${endpoint}`);
      return data;
    } catch (error) {
      logError(`API请求错误: ${endpoint}`, { error: error.message });
      throw error;
    }
  }

  /**
   * 用户注册
   * @param {Object} userData - 用户数据
   * @param {string} userData.name - 用户姓名
   * @param {string} userData.email - 用户邮箱
   * @param {string} userData.password - 用户密码
   * @returns {Promise} 注册结果Promise
   */
  async register(userData) {
    return this.request('/users/register', {
      method: 'POST',
      body: JSON.stringify(userData),
    });
  }

  /**
   * 用户登录
   * @param {Object} credentials - 登录凭据
   * @param {string} credentials.email - 用户邮箱
   * @param {string} credentials.password - 用户密码
   * @returns {Promise} 登录结果Promise
   */
  async login(credentials) {
    return this.request('/users/login', {
      method: 'POST',
      body: JSON.stringify(credentials),
    });
  }

  /**
   * 获取当前用户信息
   * @returns {Promise} 用户信息Promise
   */
  async getCurrentUser() {
    return this.request('/users/me', {
      method: 'GET',
    });
  }

  /**
   * 更新用户资料
   * @param {Object} profileData - 用户资料数据
   * @returns {Promise} 更新结果Promise
   */
  async updateProfile(profileData) {
    return this.request('/users/profile', {
      method: 'PUT',
      body: JSON.stringify(profileData),
    });
  }

  /**
   * 发送邮箱验证码
   * @param {Object} emailData - 邮箱数据
   * @param {string} emailData.email - 用户邮箱
   * @returns {Promise} 发送结果Promise
   */
  async sendVerificationCode(emailData) {
    return this.request('/users/send-verification-code', {
      method: 'POST',
      body: JSON.stringify(emailData),
    });
  }

  /**
   * 修改密码
   * @param {Object} passwordData - 密码数据
   * @param {string} passwordData.currentPassword - 当前密码
   * @param {string} passwordData.newPassword - 新密码
   * @returns {Promise} 修改结果Promise
   */
  async changePassword(passwordData) {
    return this.request('/users/change-password', {
      method: 'PUT',
      body: JSON.stringify(passwordData),
    });
  }

  /**
   * POST请求方法
   * @param {string} endpoint - API端点
   * @param {Object} data - 请求数据
   * @returns {Promise} 请求Promise
   */
  async post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }
}

// 导出API服务实例
export default new ApiService();

// 导出单独的函数以便直接调用
export const register = (userData) => new ApiService().register(userData);
export const login = (credentials) => new ApiService().login(credentials);
export const getCurrentUser = () => new ApiService().getCurrentUser();
export const updateProfile = (profileData) => new ApiService().updateProfile(profileData);
export const sendVerificationCode = (emailData) => new ApiService().sendVerificationCode(emailData);
export const changePassword = (passwordData) => new ApiService().changePassword(passwordData);
export const post = (endpoint, data) => new ApiService().post(endpoint, data);